package com.dkm.nettysocketdemo.WebSocket;

import com.dkm.nettysocketdemo.myWebsite.domain.HelmetMod;
import com.dkm.nettysocketdemo.myWebsite.service.HelmetModService;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  @ClassName : WebSocketServer  //类名
 *  @Description : socket服务  //描述
 *  @Author : 易嵘  //作者
 *  @Date: 2021-03-09 09:20  //时间
 */
@ServerEndpoint("/msgServer/{pkHelmetId}")
@Component
//scope="prototype"多例
@Scope("/prototype")
@Data
public class WebSocketServer {

    /**
     * 静态变量 用来记录当前连接数
     */
    private static int onlineCount = 0;
    /**
     * 用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();
    /***
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String pkHelmetId = "";


    /**
     * 首次连接
     * @param session webSocket会话
     * @param pkHelmetId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("pkHelmetId") String pkHelmetId) {
        this.session = session;
        System.out.println(pkHelmetId);
        String[] modId = pkHelmetId.split("_");
        if ("terminal".equals(modId[0])) {
            HelmetModService modService = ApplicationContextRegister.getApplicationContext().getBean(HelmetModService.class);
            HelmetMod mod = modService.findById(modId[1]);
            if (mod == null) {
                mod = new HelmetMod();
                mod.setPkHelmetId(modId[1]);
                mod.setIsRevision("1");
                mod.setCreatedBy("系统自动新增");
                mod.setHelmetQr(modService.getHelmetQR(modId[1]));
                modService.add(mod);
            }
        }
        if(modId.length>1){
            this.pkHelmetId = modId[1];
            webSocketMap.put(modId[1], session);
        }
    }

    @OnMessage(maxMessageSize = 56666)
    public void onMessage(String message,
                          Session session) {
        HelmetModService modService = ApplicationContextRegister.getApplicationContext().getBean(HelmetModService.class);
        try {
            System.out.println(message);
            String[] msg = message.split("_");
            if("1".equals(msg[1])){
                //判断是否是终端
                if("1".equals(msg[0])){
                    HelmetMod mod =modService.findById(msg[2]);
                    this.session.getBasicRemote().sendText("1:"+mod.getClientId());
                }else{
                    this.session.getBasicRemote().sendText("1");
                }
            }else if("0".equals(msg[1])){
                //心跳
                this.session.getBasicRemote().sendText("0");
            }else {
                sendInfo(msg[1], msg[2]);
            }
            //webSocketMap.get(entry.getKey()).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 连接异常
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 连接关闭
     * @throws IOException
     */
    @OnClose
    public void onClose() throws IOException {
    }

    /**
     * 实现服务器主动推送
     */
    /*public void SendMessage(String message) throws IOException {
        if (message.equals("心跳")) {
            this.session.getBasicRemote().sendText(message);
        }
        Enumeration<String> keys = webSocketMap.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            Session sessionvalue = webSocketMap.get(key);
            if (key.equals(this.pkHelmetId)) {
                System.out.println("my id" + key);
                String[] helmet = key.split("_");
                //1连接成功告诉客户端连接成功
                this.session.getBasicRemote().sendText("1");
                //this.sendInfo("1",key);
                //给所有人发送信息
                //sessionvalue.getBasicRemote().sendText(message);
                continue;
            }
            if (webSocketMap.get(key) == null) {
                webSocketMap.remove(key);
                System.out.println(key + ": null");
                continue;
            }
            System.out.println(key + ":id");
            if (sessionvalue.isOpen()) {
                System.out.println("发消息" + key + ",message:" + message);
                sessionvalue.getBasicRemote().sendText(message);
            } else {
                System.out.println(key + ";not open");
                sessionvalue.close();
                webSocketMap.remove(key);
            }
        }
    }*/

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, String pkHelmetId) throws IOException {
        System.out.println("发送消息到" + pkHelmetId + ",内容：" + message);
        //System.out.println(webSocketMap.containsKey(pkHelmetId));
        Enumeration<String> keys = webSocketMap.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            if (webSocketMap.get(key) == null) {
                webSocketMap.remove(key);
                //System.out.println(key + ": null");
                continue;
            }
            Session sessionvalue = webSocketMap.get(key);
            if (!sessionvalue.isOpen()) {
                //System.out.println(key + ";not open");
                sessionvalue.close();
                webSocketMap.remove(key);
            }
        }
        if (!StringUtils.isEmpty(pkHelmetId) && webSocketMap.containsKey(pkHelmetId)) {
            //System.out.println("消息发送到"+pkHelmetId);
            webSocketMap.get(pkHelmetId).getBasicRemote().sendText(message);
        } else {
            //System.out.println("用户" + pkHelmetId + ",不在线！");
        }
    }

    /**
     * 判断设备是否上线
     *
     * @param pkHelmetId
     * @return
     */
    public static Boolean isOnLine(String pkHelmetId) {
        Enumeration<String> keys = webSocketMap.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            if (pkHelmetId.equals(key)) {
                return true;
            }
        }
        return false;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
